// HotAnalysisServiceImpl.java
package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.*;
import com.scuec.groupfive.mapper.HotAnalysisMapper;
import com.scuec.groupfive.service.HotAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class HotAnalysisServiceImpl implements HotAnalysisService {

    @Autowired
    private HotAnalysisMapper hotAnalysisMapper;

    @Override
    public HotAnalysisResult getHotAnalysis(Date startDate, Date endDate, int page, int pageSize) {
        HotAnalysisResult result = new HotAnalysisResult();

        // 1. 获取总记录数（使用专门的计数查询）
        int total = hotAnalysisMapper.countTotalActiveUsers(startDate, endDate);
        result.setTotalItems(total);
        result.setCurrentPage(page);
        result.setPageSize(pageSize);

        // 2. 获取分页数据
        List<Map<String, Object>> rawData = hotAnalysisMapper.getMostActiveUsers(startDate, endDate);
        List<ActiveUser> allUsers = convertToActiveUsers(rawData);
        result.setMostActiveUsers(getPage(allUsers, page, pageSize));

        // 3. 其他数据
        result.setInteractionTrend(getInteractionTrend(startDate, endDate));
        result.setPopularTags(getPopularTags(startDate, endDate));

        return result;
    }

    private List<ActiveUser> convertToActiveUsers(List<Map<String, Object>> rawData) {
        return rawData.stream().map(item -> {
            ActiveUser user = new ActiveUser();
            user.setUserId(((Number) item.get("userId")).longValue());
            user.setName((String) item.get("name"));
            user.setPostCount(((Number) item.get("postCount")).intValue());
            user.setCommentCount(((Number) item.get("commentCount")).intValue());
            user.setLikeCount(((Number) item.get("likeCount")).intValue());
            user.setFavoriteCount(((Number) item.get("favoriteCount")).intValue());
            // 计算总活跃度
            user.setTotalActivity(
                    user.getPostCount() +
                            user.getCommentCount() +
                            user.getLikeCount() +
                            user.getFavoriteCount()
            );
            return user;
        }).collect(Collectors.toList());
    }

    private List<ActiveUser> getPage(List<ActiveUser> allUsers, int page, int pageSize) {
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, allUsers.size());
        return start >= allUsers.size() ? Collections.emptyList() : allUsers.subList(start, end);
    }

    @Override
    public HotAnalysisResult getHotAnalysis(Date startDate, Date endDate, Integer limit, int page, int pageSize) {
        return null;
    }

    @Override
    public HotAnalysisResult getHotAnalysis(Date startDate, Date endDate, int limit, int page, int pageSize) {
        return getHotAnalysis(startDate, endDate, Integer.valueOf(limit), page, pageSize);
    }

    private InteractionTrend getInteractionTrend(Date startDate, Date endDate) {
        InteractionTrend trend = new InteractionTrend();

        // 获取高峰时段
        List<Map<String, Object>> peakHours = hotAnalysisMapper.getPeakHours(startDate, endDate);
        trend.setPeakHours(peakHours.stream()
                .map(item -> (String) item.get("timeRange"))
                .collect(Collectors.toList()));

        // 获取每周模式
        List<Map<String, Object>> weeklyPattern = hotAnalysisMapper.getWeeklyPattern(startDate, endDate);
        int[] weeklyData = new int[7];
        weeklyPattern.forEach(item -> {
            int day = ((Number) item.get("dayOfWeek")).intValue();
            weeklyData[day] = ((Number) item.get("interactionCount")).intValue();
        });
        trend.setWeeklyPattern(Arrays.stream(weeklyData).boxed().collect(Collectors.toList()));

        return trend;
    }

    private List<PopularTag> getPopularTags(Date startDate, Date endDate) {
        List<Map<String, Object>> rawData = hotAnalysisMapper.getPopularTags(startDate, endDate);
        return rawData.stream().map(item -> {
            PopularTag tag = new PopularTag();
            tag.setTag((String) item.get("tag"));
            tag.setCount(((Number) item.get("count")).intValue());
            return tag;
        }).collect(Collectors.toList());
    }
}